package com.cjx.print;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.cjx.print.entity.MaterialEntity;
import com.cjx.print.entity.OrderWrap;
import com.cjx.print.helper.BluetoothHelper;
import com.cjx.print.helper.JCPrinterHelper;
import com.cjx.print.helper.XYPrinterHelper;
import com.cjx.print.utils.LogUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;

/**
 * Created by bpb on 2020-04-09.
 * 说明：am start-service -n com.cjx.print/com.cjx.print.BackgroundService
 */
public class BackgroundService extends Service {
    private static final int NOTIFICATION_ID = 10;
    private static final String CHANNEL_ID = "print_channel";
    public static final String ACTION_PRINT_TAG = "CJX.PRINT_TAG";

    public static final int MODE_FORMULA = 1; // 打印商品配方
    public static final int MODE_ORDER = 2; // 打印订单
    public static final int MODE_MATERIAL = 3; // 打印物料标签

    public static final String DATA_JSON = "DATA_JSON";
    public static final String DATA_TYPE = "DATA_TYPE";


    private BluetoothHelper bluetoothHelper;
    private JCPrinterHelper jcPrinterHelper;
    private XYPrinterHelper xyPrinterHelper;

    private boolean tagConnectStatus = false;
    private boolean receiptConnectStatus = false;

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                int mode = intent.getIntExtra(DATA_TYPE, 0);
                String json = intent.getStringExtra(DATA_JSON);
                LogUtil.getInstance().log("SERVER", "收到信息 " + ACTION_PRINT_TAG + " mode: " + mode + ", json: " + json);

                switch (mode) {
                    case MODE_ORDER:
                        OrderWrap orderWrap = new Gson().fromJson(json, new TypeToken<OrderWrap>() {
                        }.getType());
                        if (jcPrinterHelper != null) {
                            jcPrinterHelper.printOrderLabel(orderWrap.serialNumber, orderWrap.time, orderWrap.goodsList);
                        }
                        if (xyPrinterHelper != null) {
                            xyPrinterHelper.printOrderLabel(orderWrap.serialNumber, orderWrap.time, orderWrap.goodsList);
                        }
                        break;
                    case MODE_MATERIAL:
                        MaterialEntity material = new Gson().fromJson(json, new TypeToken<MaterialEntity>() {
                        }.getType());
                        if (jcPrinterHelper != null) {
                            jcPrinterHelper.printMaterialTag(material);
                        }
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private final Handler protectHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            protectHandler.removeMessages(0);
            protectHandler.sendEmptyMessageDelayed(0, 5000);
            Intent intent = new Intent(App.ACTION_PRINTER_CONNECT_STATUS);
            intent.putExtra("tag_status", tagConnectStatus);
            intent.putExtra("receipt_status", receiptConnectStatus);
            sendBroadcast(intent);

            return false;
        }
    });

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.getInstance().initLogFile(this, Constants.FILE_LOG_RUN_DIR);
        LogUtil.getInstance().log("打印服务", "创建了服务");
        // 如果是 Android 8.0 及以上，必须创建前台服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(NOTIFICATION_ID, buildNotification());
        }
        try {
            unregisterReceiver(receiver);
        } catch (Exception ignore) {
        }
        registerReceiver(receiver, new IntentFilter(ACTION_PRINT_TAG));

        protectHandler.sendEmptyMessageDelayed(0, 5000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String modeString = intent.getStringExtra("tag");

            String type = intent.getStringExtra("type");
            if (modeString != null) {
                int mode = Integer.parseInt(modeString);
                if (jcPrinterHelper != null) {
                    jcPrinterHelper.disconnect();
                    jcPrinterHelper = null;
                }
                if (xyPrinterHelper != null) {
                    xyPrinterHelper.closeTagDevice();
                    xyPrinterHelper = null;
                }
                connect(true, mode, type);
            } else {
                modeString = intent.getStringExtra("receipt");
                if (modeString != null) {
                    int mode = Integer.parseInt(modeString);
                    if (xyPrinterHelper != null) {
                        xyPrinterHelper.closeReceiptDevice();
                    }
                    connect(false, mode, type);
                }
            }
        }
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (jcPrinterHelper != null) {
            jcPrinterHelper.disconnect();
            jcPrinterHelper = null;
        }
        if (xyPrinterHelper != null) {
            xyPrinterHelper.closeTagDevice();
            xyPrinterHelper.closeReceiptDevice();
            xyPrinterHelper = null;
        }
        unregisterReceiver(receiver);
        LogUtil.getInstance().log("SERVER", "销毁服务");
    }


    private Notification buildNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "YL-Print",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("YL-Print")
                .setContentText("Running")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build();
    }

    private void connect(boolean isTag, int mode, String type) {
        new Thread() {
            @Override
            public void run() {
                if (Constants.MODE_TAG_JC_B3S == mode) { // 精臣打印机， 只支持蓝牙
                    startJCPrinter();
                } else {
                    if ("0" .equals(type)) {
                        startXYPrinterBluetooth(isTag, mode);
                    } else {
                        startXYPrinterUSB(isTag, type);
                    }
                }
            }
        }.start();
    }

    private void startJCPrinter() {
        bluetoothHelper = BluetoothHelper.getInstance();
        jcPrinterHelper = JCPrinterHelper.getInstance();
        retryCount = 0;
        if (bluetoothHelper.openBluetooth()) {
            bluetoothHelper.setDeviceHandlerCallback(d -> {
                if (d == null) {
                    System.out.println("---------------结束了 连接状态：" + tagConnectStatus);
                    LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(tagConnectStatus);
                    return;
                }
                String deviceName = d.getName();
                if (d.getType() == 1 && deviceName != null && (deviceName.startsWith("B3S-") || deviceName.startsWith("B3S_P-"))) {
                    System.out.println("识别到设备 " + d.getName() + ", " + d.getAddress() + ", " + d.getType() + ", " + new Gson().toJson(d.getBluetoothClass()));
                    bluetoothHelper.stopScan();
                    jcPrinterHelper.connectDevice(d.getAddress(), 1000, success -> {
                        tagConnectStatus = success;
                        LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(success);
                    });
                }
            });
            bluetoothHelper.startScan();
        }
    }

    int retryCount = 0;

    private void startXYPrinterBluetooth(boolean isTag, int mode) {
        xyPrinterHelper = XYPrinterHelper.getInstance();
        bluetoothHelper = BluetoothHelper.getInstance();
        if (bluetoothHelper.openBluetooth()) {
            retryCount = 0;
            bluetoothHelper.setDeviceHandlerCallback(d -> {
                if (d == null) {
                    retryCount++;
                    if (isTag) {
                        System.out.println("---------------结束了 连接状态：" + tagConnectStatus);
                        LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(tagConnectStatus);
                    } else {
                        System.out.println("---------------结束了 连接状态：" + receiptConnectStatus);
                        LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(receiptConnectStatus);
                    }
                    return;
                }
                String deviceName = d.getName();
                if (d.getType() == 1 && deviceName != null) {
                    if (isTag) {
                        String nameMode = "XP-T271U";
                        System.out.println("扫描 >> " + deviceName + " -- " + nameMode);
                        if (deviceName.equals(nameMode)) {
                            bluetoothHelper.stopScan();
                            xyPrinterHelper.connectTagBluetooth(d.getAddress(), success -> {
                                tagConnectStatus = success;
                                LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(success);
                            });
                        }
                    } else {
                        System.out.println("扫描》" + deviceName);
                        if (deviceName.startsWith("Printer")) {
                            bluetoothHelper.stopScan();
                            xyPrinterHelper.connectReceiptBluetooth(d.getAddress(), success -> {
                                receiptConnectStatus = success;
                                LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(success);
                            });
                        }
                    }
                }
            });
            bluetoothHelper.startScan();
        }
    }

    private void startXYPrinterUSB(boolean tag, String path) {
        xyPrinterHelper = XYPrinterHelper.getInstance();
        if (!TextUtils.isEmpty(path)) {
            if (tag) {
                xyPrinterHelper.connectTagUSB(path, success -> {
                    tagConnectStatus = success;
                    LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(success);
                });
            } else {
                xyPrinterHelper.connectReceiptUSB(path, success -> {
                    receiptConnectStatus = success;
                    LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(success);
                });
            }
        } else {
            LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(false);
        }
    }
}
